package com.bankcomm.voice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.bankcomm.R;
import com.xioai.framework.api.jsonbean.Plugin;
import com.xioai.framework.api.jsonbean.Response;
import com.xioai.framework.common.spellindex.contacts.ContactsSearch;
import com.xioai.framework.common.spellindex.contacts.PhoneNumSearchResults;
import com.xioai.framework.common.spellindex.util.StringUtil;
import com.xioai.framework.voicecontrol.VoiceControl;

/**
 * 对话交互碎片
 * 
 * @author liujia (liujia9234@126.com)
 * @data @2012-2-17
 * @version 1.0
 *          <ul>
 *          <li>1.0 创建</li>
 *          </ul>
 */
// 中间TextView中显示的Talk fragment
public class TalkFragment extends Fragment {
	public static final String TAG = "TalkFragment";
	private Map<String, View> map = new HashMap<String, View>();//存储要移除的VIEW
	private VoiceControl vc;
	private List<TalkBean> talkBeans = new ArrayList<TalkBean>();
	private Handler mHandler = new Handler();
	private boolean btnShow=false;
	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1);

	public TalkFragment(VoiceControl vc) {
		super();
		this.vc = vc;
	}

	private ScrollView scrollView;
	private LinearLayout layout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		layout.removeAllViews();
		for (TalkBean tb : talkBeans) {
			if (getActivity() != null) {
				addTalkView(tb);
			}
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		scrollView = (ScrollView) getActivity().findViewById(R.id.talk_sv);
		
		layout = (LinearLayout) getActivity().findViewById(R.id.talk_content_layout);
		
		scrollView.setHorizontalScrollBarEnabled(false);
		scrollView.setVerticalScrollBarEnabled(false);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.xiaoi_talk, null);
	}

	/**
	 * 增加一个对话信息
	 * 
	 * @param tb
	 */
	public void addCurrTalkText(TalkBean<?> tb) {
		talkBeans.add(tb);
		if (getActivity() != null) {
			addTalkView(tb);
		}
	}

	/**
	 * 增加对话信息预加载列表中
	 * 
	 * @param tb
	 */
	public void addTalkText(TalkBean<?> tb) {
		talkBeans.add(tb);
	}

	/**
	 * 创建对话视图
	 * 
	 * @param tb
	 */
	public void addTalkView(TalkBean<?> tb) {
		params.setMargins(0, 6, 0, 0);
       
		TalkContro talkExpand = new TalkContro(getActivity());//对话
		talkExpand.setLayoutParams(params);
		
		if (tb != null && tb.getType() == TalkBean.SAY_ME) {
			talkExpand.backPIC(R.drawable.xiaoi_talk_bg);
			
			Animation talk_me = new TranslateAnimation(0, 0,scrollView.getHeight(), 0);
			talk_me.setInterpolator(getActivity(),android.R.anim.anticipate_overshoot_interpolator);//动画
			talk_me.setDuration(700);

			if (tb.getBean() instanceof String) {

				talkExpand.setText('"' + tb.getBean().toString() + '"');
				layout.addView(talkExpand);

			}
			talkExpand.startAnimation(talk_me);
		} else {

			if (tb.getBean() instanceof Response) {
				final Response response = (Response) tb.getBean();
				if (response.getContent() != null&& !StringUtil.isBlank(response.getContent())) {
					
					talkExpand.backPIC(R.drawable.xiaoi_talk_bg);
					Animation talk_he = new TranslateAnimation(scrollView.getWidth(), 0, 0, 0);
					talk_he.setInterpolator(getActivity(),android.R.anim.accelerate_interpolator);//动画
					talk_he.setDuration(1000);
					
					talkExpand.setText(response.getContent());
					layout.addView(talkExpand);
					mHandler.post(execute());
					
					talkExpand.startAnimation(talk_he);
				}
				if (response.getPlugin() != null) {
					 
					layout.removeView(map.get("button"));//移除
					layout.removeView(map.get("plugin"));
					
					if (map.size() > 0) {
						map.remove("button");
						map.remove("plugin");
					}
					
				     //显示转账相关联系人列表
					if (response.getPlugin().getName() != null) {
						if ("contacts".equalsIgnoreCase(response.getPlugin().getName())) {
							String numberFilter = "";
							if (response.getPlugin().getArgs().size() > 3) { // 判断是否有号码过滤器
								numberFilter = response.getPlugin().getArgs().get(3);
							}
							//找到联系人的个数
							PhoneNumSearchResults pnsr = ContactsSearch.getInstance(getActivity()).searchPhone(response.getPlugin().getArgs().get(0), numberFilter);

							  if(pnsr != null && pnsr.getPhones() != null && pnsr.isAccurate()&&pnsr.getPhones().size()==1)
							  {
								  String servicesStr=response.getPlugin().getArgs().get(1);
									servicesStr=servicesStr.replace("{1}", pnsr.getPhones().get(0).getName().replace("-", ""));
									servicesStr=servicesStr.replace("{0}", pnsr.getPhones().get(0).getPhoneNum().replace("-", ""));
									vc.askData(servicesStr);
							  }else if (pnsr != null && pnsr.getPhones() != null && pnsr.getPhones().size() > 0) {
								//替换对话
								String contacts = response.getPlugin().getArgs().get(2).replace("{0}",String.valueOf(pnsr.getPhones().size()));
								talkExpand.backPIC(R.drawable.xiaoi_talk_bg);
								Animation talk_he = new TranslateAnimation(scrollView.getWidth(), 0, 0, 0);
								talk_he.setInterpolator(getActivity(),android.R.anim.accelerate_interpolator);//动画
								
								talk_he.setDuration(1000);
								talkExpand.setText(contacts);
								layout.addView(talkExpand);
								
								vc.startPlayer(contacts);//播放语音
								mHandler.post(execute());
								talkExpand.startAnimation(talk_he);
								TalkContacts t;
								layout.addView(t = new TalkContacts(getActivity(),vc, response));
								map.put("plugin", t);
								btnShow=true;
							}else
							{   
								String servicesStr=response.getPlugin().getArgs().get(1);
								servicesStr=servicesStr.replace("{1}", "");
								servicesStr=servicesStr.replace("{0}", "");
								vc.askData(servicesStr);
							}
						}

					}
				}
				//转账给其它人按钮
				if (response.getButtons() != null&&btnShow) {
					Plugin plugin = response.getPlugin();
					String pluginCmd = "";
					if(plugin != null){
						pluginCmd = plugin.getName();
					}
					if (response.getButtons().length > 0 && !"sms".equals(pluginCmd)) {
                        //布局
						LinearLayout btnLayout = (LinearLayout) ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.xiaoi_talk_buttton, null);
						final Button btn = (Button) btnLayout.findViewById(R.id.talk_btn);
						LinearLayout.LayoutParams btnP = new LinearLayout.LayoutParams(-1, -2);
						try {
							btn.setText(response.getButtons()[0].getCaption());
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
						btn.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub

								btn.setTextColor(R.color.talk_contacts_click_text);
								vc.askData(response.getButtons()[0].getParams());//发回数据
							}
						});
						layout.addView(btnLayout, btnP);
						mHandler.post(execute());
						map.put("button", btnLayout);
						btnShow=false;
					}
				}

			}
		}

	}

	/**
	 * 滚动条 显示最新信息
	 */
	private Runnable execute() {
		Runnable scrollToRun = new Runnable() {

			@Override
			public void run() {
				int off = layout.getMeasuredHeight() - scrollView.getHeight();
				if (off > 0) {
					scrollView.scrollTo(0, off);

				}

			}
		};
		return scrollToRun;
	}

}
